package com.shujia.core

import org.apache.spark.rdd.RDD
import org.apache.spark.{SparkConf, SparkContext}

import scala.util.Random

object Demo20PI {
  def main(args: Array[String]): Unit = {
    val conf: SparkConf = new SparkConf()
//      .setMaster("local")
      .setAppName("计算pi的值")

    val sc: SparkContext = new SparkContext(conf)

    val range1: Range.Inclusive = 1 to 100000000
    val listRDD1: RDD[Int] = sc.parallelize(range1)
    //map一下listRDD1，就可以得到循环100000次的特点
    val zuoBiaoRDD: RDD[(Double, Double)] = listRDD1.map((i: Int) => {
      val x: Double = Random.nextDouble() * 2 - 1
      val y: Double = Random.nextDouble() * 2 - 1
      (x, y)
    })


    val yuanZuoBiaoRDD: RDD[(Double, Double)] = zuoBiaoRDD.filter((zb: (Double, Double)) => {
      //过滤出圆中点，x轴的平方加上y轴的平方小于等于1
      Math.pow(zb._1, 2) + Math.pow(zb._2, 2) <= 1
    })


    //计算PI圆周率的值
    println("-------------------------------------------------------------------------")
    println(s"圆周率为：${yuanZuoBiaoRDD.count().toDouble / zuoBiaoRDD.count().toDouble * 4}")
    println("-------------------------------------------------------------------------")

  }
}
